﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Yule8xCommon.Applib;
using Yule8xCommon.Db;
using Yule8xCommon.Typelib;
using Yule8xModel;
using Yule8xWechat.Applib;

namespace Yule8xWechat.PublicServices
{
    public partial class SMSServices : System.Web.UI.Page
    {
        protected WxUserInfoResult wxUser = null;
        protected void Page_Load(object sender, EventArgs e)
        {
            // 判断登录
            object loginData = Session["login"];
            if (null != loginData)
            {
                wxUser = loginData as WxUserInfoResult;
            }
            if (null == loginData || null == wxUser)
            {
                LogUtil.Instance.WriteInfo("[短信公共接口] 未登录");
                Response.Write("登录超时或未登录");
                Response.End();
            }

            string type = RequestUtil.GetString("type", maxLen: 32);
            string mobile = RequestUtil.GetString("mobile", maxLen: 16);
            string errtip = "";
            if (string.IsNullOrEmpty(mobile))
            {
                mobile = UserModels.GetMobile(wxUser.user_id);
            }
            int uid = RequestUtil.GetInteger("uid");
            string tplValue = string.Empty, msg = string.Empty;
            if (string.IsNullOrEmpty(mobile) || uid < 1 || string.IsNullOrEmpty(type))
            {
                Response.Write("验证码参数错误!");
                Response.End();
            }
            if (!RegularUtil.IsMatch(mobile, RegularUtil.Rules.MobileNumber))
            {
                Response.Write("手机号码无效!");
                Response.End();
            }
            if (type.IndexOf("confirm") > -1)
            {
                Random rnd = new Random();
                string code = rnd.Next(1000, 9999).ToString();
                tplValue = "#code#=" + code;
                UserCaptchaModels.AddCaptcha(uid, code, DateTime.Now.AddSeconds(AppConf.SMSExpireTime), type);
                msg = SMSUtil.SendForConfirm(mobile, Server.UrlEncode(tplValue));
                if (msg.IndexOf("成功") > -1)
                {
                    msg = "验证码发送成功!";
                }
            }
            Response.Write(msg);
            Response.End();
        }
    }
}